from django.db.models import Q
from django.shortcuts import render
from django.http.response import HttpResponse, JsonResponse
from rest_framework import mixins, viewsets
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet

# Create your views here.

# 造车 --> 原材料
#
from goods_info.attachment_serializer import AttachmentsSerializer
from goods_info.models import GoodsCategoryModel, UnitsModel, AttachmentModel, GoodsModel
from goods_info.serializer import CategorySerializer, UnitsSerializer, GoodsBaseSerializer
from user.views import MultipleDestroyMixin


def test():
    return HttpResponse("OK")


class CategoryView(ModelViewSet):
    """
    create:
    货品类别--新增

    货品类别新增, status: 201(成功), return: 新增货品类别信息

    destroy:
    货品类别--删除

    货品类别删除, status: 204(成功), return: None

    multiple_delete:
    货品类别--批量删除,必传参数：ids=[1,2,3,4...]

    货品类别批量删除, status: 204(成功), return: None

    update:
    货品类别--修改,

    货品类别修改, status: 200(成功), return: 修改后的货品类别信息

    partial_update:
    货品类别--局部修改,可以传参任意属性的值，服务器会修改指定的属性值

    货品类别局部修改, status: 200(成功), return: 修改后的货品类别信息

    list:
    货品类别--获取类别列表，可选get请求参数:pid，如果没有传，则查询顶级类别，否则查询指定pid下的子类别

    货品类别列表信息, status: 200(成功), return: 货品类别信息列表

    retrieve:
    查询某一个货品类别

    查询指定ID的货品类别, status: 200(成功), return: 用户货品类别
    """

    queryset = GoodsCategoryModel.objects.all()
    serializer_class = CategorySerializer

    def get_queryset(self):
        if self.action == 'list':  # 判断是否查询顶级列表还是某个子列表
            # 获取请求参数(在get中)：pid
            pid = self.request.query_params.get('pid', None)
            if pid and pid != '0':
                return GoodsCategoryModel.objects.filter(parent__id=int(pid)).all()
            return GoodsCategoryModel.objects.filter(parent__isnull=True).all()
        else:
            return GoodsCategoryModel.objects.all()

    # 分页参数必须是query_param(看源码)

    def list(self, request, *args, **kwargs):
        return super(CategoryView, self).list(request=request, *args, **kwargs)


class UnitsView(ModelViewSet):
    """
    create:
    计量类别--新增

    计量类别新增, status: 201(成功), return: 新增计量类别信息

    destroy:
    计量类别--删除

    计量类别删除, status: 204(成功), return: None

    multiple_delete:
    计量类别--批量删除,必传参数：ids=[1,2,3,4...]

    计量类别批量删除, status: 204(成功), return: None

    update:
    计量类别--修改,

    计量类别修改, status: 200(成功), return: 修改后的计量类别信息

    partial_update:
    计量类别--局部修改,可以传参任意属性的值，服务器会修改指定的属性值

    计量类别局部修改, status: 200(成功), return: 修改后的计量类别信息

    list:
    计量类别--获取类别列表，可选get请求参数:pid，如果没有传，则查询顶级类别，否则查询指定pid下的子类别

    计量类别列表信息, status: 200(成功), return: 计量类别信息列表

    retrieve:
    查询某一个计量类别

    查询指定ID的计量类别, status: 200(成功), return: 用户计量类别
    """

    queryset = UnitsModel.objects.all()
    serializer_class = UnitsSerializer

    def get_queryset(self):
        if self.action == 'find':  # 判断是否查询顶级列表还是某个子列表
            # 获取请求参数(在get中)：pid
            keyword = self.request.data.get('name', None)
            query = Q()
            if keyword:
                query.add(Q(basic_name__contains=keyword), "OR")
                query.add(Q(backup_name__contains=keyword), "OR")
            return UnitsModel.objects.filter(query).all()
        else:
            return UnitsModel.objects.all()

    # 分页参数必须是query_param(看源码)
    @action(methods=['POST'], detail=False)
    def find(self, request, *args, **kwargs):
        return super(UnitsView, self).list(request=request, *args, **kwargs)


class AttachmentView(mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.ReadOnlyModelViewSet):
    """
    create:
    附件或者图片--新增。a_file：必须是选择的一个文件， a_type:是一个字符串，参考模型类代码

    附件或者图片新增, status: 201(成功), return: 新增附件或者图片信息

    destroy:
    附件或者图片--删除

    附件或者图片删除, status: 204(成功), return: None

    list:
    附件或者图片--获取分页列表

    附件或者图片列表信息, status: 200(成功), return: 附件或者图片信息列表

    retrieve:
    查询某一个附件或者图片

    查询指定ID的附件或者图片, status: 200(成功), return: 用户附件或者图片
    """

    queryset = AttachmentModel.objects.all()
    serializer_class = AttachmentsSerializer







# class GoodsView(viewsets.ModelViewSet, MultipleDestroyMixin, MultipleOpenMixin):
#     """
#     create:
#     货品(商品)信息--新增,注意：其中images_list="1,2,3,4";里面是附件的ID
#
#     货品(商品)信息新增, status: 201(成功), return: 新增货品(商品)信息信息
#
#     destroy:
#     货品(商品)信息--删除
#
#     货品(商品)信息删除, status: 204(成功), return: None
#
#     multiple_delete:
#     货品(商品)信息--批量删除,必传参数：ids=[1,2,3,4...]
#
#     货品(商品)信息批量删除, status: 204(成功), return: None
#
#     multiple_open:
#     货品(商品)信息--批量启用或者禁用,必传(json)参数：ids=[1,2,3,4...](列表中可以只有一个)，is_open=1/0
#
#     {
#         "ids":[1,2],
#         "is_open":"0"
#     }
#     is_open=1表示禁用，is_open=0表示启用，
#     货品(商品)信息批量启用或者禁用, status: 204(成功), return: None
#
#     update:
#     货品(商品)信息--修改,注意：其中images_list="1,2,3,4";里面是附件的ID
#
#     货品(商品)信息修改, status: 200(成功), return: 修改后的货品(商品)信息信息
#
#     partial_update:
#     货品(商品)信息--局部修改,可以传参任意属性的值，服务器会修改指定的属性值
#
#     货品(商品)信息局部修改, status: 200(成功), return: 修改后的货品(商品)信息信息
#
#     list:
#     货品(商品)信息--该接口可以弃用
#
#     货品(商品)信息列表信息, status: 200(成功), return: 货品(商品)信息信息列表
#
#     retrieve:
#     查询某一个货品(商品)信息
#
#     查询指定ID的货品(商品)信息, status: 200(成功), return: 用户货品(商品)信息
#     """
#
#     queryset = GoodsModel.objects.all()
#     serializer_class = GoodsBaseSerializer
#     # pagination_class = GlobalPagination
#
#     def get_queryset(self):
#         if self.action == 'find':  # 过滤查询
#             # 获取请求参数(在json中)：
#             keyword = self.request.data.get('keyword', None)
#             color = self.request.data.get('color', None)
#             category = self.request.data.get('category', 0)
#             number_code = self.request.data.get('number_code', None)
#             basic_weight = self.request.data.get('basic_weight', None)
#             expiration_day = self.request.data.get('expiration_day', 0)
#             delete_flag = self.request.data.get('delete_flag', None)
#             query = Q()
#             if keyword:
#                 child_query = Q()
#                 child_query.add(Q(name__contains=keyword), 'OR')
#                 child_query.add(Q(specification=keyword), 'OR')
#                 child_query.add(Q(model_number=keyword), 'OR')
#                 query.add(child_query, 'AND')
#             if color:
#                 query.add(Q(color=color), 'AND')
#             if category:
#                 query.add(Q(category__id=category), 'AND')
#             if number_code:
#                 query.add(Q(number_code__contains=number_code), 'AND')
#             if basic_weight:
#                 query.add(Q(basic_weight=basic_weight), 'AND')
#             if expiration_day:
#                 query.add(Q(expiration_day=expiration_day), 'AND')
#             if delete_flag:
#                 query.add(Q(delete_flag=delete_flag), 'AND')
#             return GoodsModel.objects.filter(query).all()
#         else:
#             return GoodsModel.objects.all()
#
#     def get_serializer_class(self):
#         if self.action == 'retrieve' or self.action == 'find':
#             return GoodsGetSerializer
#         return GoodsBaseSerializer
#
#     params = openapi.Schema(type=openapi.TYPE_OBJECT, properties={
#         'keyword': openapi.Schema(type=openapi.TYPE_STRING, description="名称的关键字或者规格和型号"),
#         'color': openapi.Schema(type=openapi.TYPE_STRING, description="颜色"),
#         'number_code': openapi.Schema(type=openapi.TYPE_STRING, description="批号(序列号)"),
#         'basic_weight': openapi.Schema(type=openapi.TYPE_STRING, description="基础质量"),
#         'delete_flag': openapi.Schema(type=openapi.TYPE_STRING, description="状态0或者1"),
#         'category': openapi.Schema(type=openapi.TYPE_INTEGER, description="类别的ID"),
#         'expiration_day': openapi.Schema(type=openapi.TYPE_INTEGER, description="保质期天数"),
#     })
#     # 分页参数必须是query_param(看源码)
#     page_param = openapi.Parameter(name='page', in_=openapi.IN_QUERY, description="页号", type=openapi.TYPE_INTEGER)
#     size_param = openapi.Parameter(name='size', in_=openapi.IN_QUERY, description="每页显示数量", type=openapi.TYPE_INTEGER)
#
#     @swagger_auto_schema(method='POST', request_body=params, manual_parameters=[page_param, size_param],
#                          operation_description="商品搜索过滤")
#     @action(methods=['POST'], detail=False)
#     def find(self, request, *args, **kwargs):
#         return super(GoodsView, self).list(request=request, *args, **kwargs)
